package com.tchintech.pay.view.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.tchintech.pay.R;
import com.tchintech.pay.adapter.FullyGridLayoutManager;
import com.tchintech.pay.adapter.RecycleCodeAdapter;
import com.tchintech.pay.adapter.SpaceBaseItemDecoration;
import com.tchintech.pay.delegate.CodeReceiveDelegate;
import com.tchintech.pay.frame.presenter.ActivityPresenter;
import com.tchintech.pay.model.entity.HttpCode;
import com.tchintech.pay.model.entity.PaytypeResule;
import com.tchintech.pay.sqllite.OperateSql;
import com.tchintech.pay.utils.AppConst;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2017/7/11 0011.
 * 二维码支付
 */

public class CodeReceiveActivity extends ActivityPresenter<CodeReceiveDelegate> implements OnClickListener {

    private RecyclerView recyclerView;
    private RecycleCodeAdapter adapter;
    private List<PaytypeResule> list;

    private Intent intent;

    //保存当前activity
    public static List<Activity> activityList;
    protected HashMap<String, String> map;
    private String urlCcode = "Order/scancode";
    private String urlSubmit = "Order/create";
    private Handler handler;
    /**
     * //获取　姓名　和　手机的组件
     */
    private TextView tv_name, tv_phone;
    /**
     * 获取输入的金额
     */
    private EditText editText;

    private OperateSql operateSql;
    /**
     * 选中的支付方式到账方式
     */
    private String payType, arrivalType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        super.initView();
        viewDelegate.setVisible();
        editText = viewDelegate.getEdit();
        viewDelegate.setOnClickListener(this, R.id.iv_back, R.id.bt_next);
        recyclerView = viewDelegate.getRecycle();
        //设置gridLayout 样式
        recyclerView.setLayoutManager(new FullyGridLayoutManager(this, 3));
        adapter = new RecycleCodeAdapter(this, list);
        recyclerView.setAdapter(adapter);
        //设置recycle的间距一致
        recyclerView.addItemDecoration(new SpaceBaseItemDecoration(3));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        Listener();
        handler();

    }


    @Override
    protected void initData() {
        super.initData();
        intent = new Intent();
        list = new ArrayList<PaytypeResule>();
        viewDelegate.setTitle("二维码收款");
        viewDelegate.getTextviews(R.id.tv_name).setText(AppConst.getUser().getUsername());
        viewDelegate.getTextviews(R.id.tv_phone).setText(AppConst.getUser().getPhone());
        //queryCode();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.bt_next:
                judgeMony();
                break;

        }

    }

    /**
     * recycleView的点击事件
     */
    private void Listener() {
        adapter.setOnItemClickLitener(new RecycleCodeAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(PaytypeResule paytype, int position) {
                adapter.changeColor(position);
                payType = paytype.getPayType();
                arrivalType = paytype.getArrivalType();
            }
        });
    }

    /**
     * 获取支付方式和支付方式
     */
    private void queryCode() {
        map = new HashMap<String, String>();
        httpPost(urlCcode, map, HttpCode.orderSpPayType, null);
    }


    /**
     * 执行下一步时  判断输入的金额
     */
    private void judgeMony() {
        activityList = new ArrayList<Activity>();
        String money = editText.getText().toString().trim();
        String[] moneys = (money.replace(".", " ")).split(" ");
        if (moneys.length < 3 && !money.equals("")) {
            float moneyf = Float.parseFloat(money);
            if (moneyf >= 10.00) {
                submit(money);
            } else {
                showMsg("输入金额不得低于10元");
            }
        } else {
            showMsg("输入的金额不合法");
        }

    }

    /**
     * 下一步提交
     */
    private void submit(String money) {
        map = new HashMap<String, String>();
        map.put("amount", money);
        map.put("payType", payType);
        map.put("arrivalType", arrivalType);
        map.put("qrCodeType", "DYNAMIC");
        map.put("merchantName", "qizhineng");
        httpPost(urlSubmit, map, HttpCode.codereceive, null);
    }


    @Override
    public void httpCallback(String resultBean, int what) {
        super.httpCallback(resultBean, what);
        Message msg = new Message();
        switch (what) {
            case HttpCode.codereceive:
                try {
                    JSONObject json = new JSONObject(resultBean);
                    if (json.getString("result").equals(SUCCESS)) {
                        msg.obj = json.getString("qrcodeInfo");
                        msg.what = HttpCode.codereceive_SUCCESS;
                    } else {
                        msg.obj = "提交失败";
                        msg.what = HttpCode.codereceive_FAILE;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.sendMessage(msg);
                break;
            case HttpCode.orderSpPayType:
                System.out.println("查询的支付方式" + resultBean);
                if (resultBean.equals("")) {
                    msg.what = HttpCode.orderSpPayType_FAILE;
                    msg.obj = "查询支付方式失败";
                } else {
                    msg.what = HttpCode.orderSpPayType_SUCCESS;
                    msg.obj = resultBean;
                }

                handler.sendMessage(msg);
                break;
            case HttpCode.networkabnormal:
                handler.sendEmptyMessage(HttpCode.networkabnormal);
                break;


        }
    }


    private void handler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case HttpCode.networkabnormal:
                        showMsg("当前网络不可用");
                        break;
                    case HttpCode.http_failed:
                        showMsg("连接失败");
                        break;
                    case HttpCode.http_timeout:
                        showMsg("请求超时");
                        break;
                    case HttpCode.orderSpPayType_SUCCESS:
                        String jsoStr = msg.obj.toString();
                        try {
                            JSONArray jsonArray = new JSONArray(jsoStr);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject json = jsonArray.getJSONObject(i);
                                if (i == 0) {
                                    //设置默认选中的值
                                    payType = json.getString("payType");
                                    arrivalType = json.getString("arrivalType");
                                }
                                PaytypeResule paytypeResule = new PaytypeResule();
                                paytypeResule.setPayType(json.getString("payType"));
                                paytypeResule.setArrivalType(json.getString("arrivalType"));
                                list.add(paytypeResule);
                            }
                            adapter.setData(list);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case HttpCode.codereceive_SUCCESS:
                        String str = msg.obj.toString();
                        activityList.add(CodeReceiveActivity.this);
                        intent.setClass(CodeReceiveActivity.this, CodeActivity.class);
                        intent.putExtra("code", str);
                        intent.putExtra("payType", payType);
                        startActivity(intent);
                        break;
                    case HttpCode.codereceive_FAILE:
                        showMsg(msg.obj.toString());
                        break;

                    case HttpCode.orderSpPayType_FAILE:
                        showMsg(msg.obj.toString());
                        break;
                }
            }
        };
    }


    @Override
    protected Class<CodeReceiveDelegate> getDelegateClass() {
        return CodeReceiveDelegate.class;
    }


}
